package app

import (
	"context"
	"github.com/jinzhu/copier"
	"web_server/internal/model"
	"web_server/internal/svc"
	"web_server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type WordsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewWordsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WordsLogic {
	return &WordsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *WordsLogic) WordSearch(req *types.WordSearchRequest) ([]*types.WordsResponse, error) {
	var result []*types.WordsResponse = make([]*types.WordsResponse, 0)
	var err error = nil
	if req.Word == "" {
		return result, nil
	}
	var wordSearch []*model.Words
	wordSearch, err = l.svcCtx.MysqlClient.WordsModel.WordSearch(l.ctx, req.Word)
	if err != nil {
		return nil, err
	}
	for _, item := range wordSearch {
		var wordItem types.WordsResponse = types.WordsResponse{}
		err = copier.Copy(&wordItem, &item)
		if err != nil {
			continue
		}
		result = append(result, &wordItem)
	}

	return result, nil
}

func (l *WordsLogic) WordDetail(req *types.PublicPathIdRequest) (*types.WordsResponse, error) {
	item, err := l.svcCtx.MysqlClient.WordsModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, err
	}
	var result types.WordsResponse = types.WordsResponse{}
	copyErr := copier.Copy(&result, &item)
	if copyErr != nil {
		return nil, copyErr
	}
	return &result, nil
}
